import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class LoginResult extends HttpServlet {
    private static final long serialVersionUID = 2876366402613815741L;

    @Override
    public void init(ServletConfig config) {
        System.out.println("初始化servlet");
    }

    @Override
    public void destroy() {
        System.out.println("销毁servlet");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 如果请求的方式为get，重定向至登录页
        resp.sendRedirect("login.html");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        String usr = req.getParameter("usr");
        String pwd = req.getParameter("pwd");
        PrintWriter out = resp.getWriter();
        if (usr.equals("admin") && pwd.equals("admin")) {
            out.print("成功登录<br>");
            out.print("IP地址：" + req.getRemoteAddr());
        } else {
            out.print("用户名或密码错误<br>");
            out.print("返回<a href='login.html'>登录页</a>");
        }
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=UTF-8");
        PrintWriter out = resp.getWriter();
        out.print("<!DOCTYPE html>");
        out.print("<html>");
        out.print("<head>");
        out.print("<meta charset='UTF-8'>");
        out.print("<title>登录状态</title>");
        out.print("</head>");
        out.print("<body>");
        super.service(req, resp);
        out.print("</body>");
        out.print("</html>");
    }
}
